const api = require('../../../utils/api.js');
const regeneratorRuntime = require('../../../utils/runtime.js');
const config = require('../../../utils/config.js')
const util = require('../../../utils/utils.js');

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholder: "赶快创作你的作品吧...",
    post: {},
    imgList: [],
    fileList: [],
    isShowModel: false,
    isFileChanged: false,
    isImgChanged: false,

    colleges: [],
    collegeIndex: 0,
    majorIndex: 0,

    content: '',

    courseInfo: [
      [],
      ['大一', '大二', '大三', '大四', '大五', '研一', '研二'],
      ['上学期', '下学期'],
      ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
    ],
    courseIndex: [0, 0, 0, 0],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    let that = this;
    let blogId = options.id;
    console.info('input id -> ', blogId)

    let result = await api.getCollegeList(1, {})
    console.log('colleges ->', result)
    if (result.data.length > 0) {
      this.setData({
        colleges: result.data
      })
    }

    // result = await api.getGradeList(1, {})
    // if (result.data.length > 0) {
    //   let ms = []
    //   for (var i in result.data) {
    //     ms.push(result.data[i].name)
    //   }
    //   let cInfo = this.data.courseInfo
    //   cInfo[1] = ms
    //   this.setData({
    //     courseInfo: cInfo
    //   })
    // }

    this.initCourseInfo()

    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context
    }).exec()
    if (blogId !== undefined) {
      let result = await api.getPostsById(blogId)
      that.setData({
        post: result.data,
        imgList: that.data.imgList.concat({
          originPath: result.data.image,
          httpPath: api.convertCloud2Http(result.data.image),
        }),
        fileList: that.data.fileList.concat(result.data.attach),
      });
      this.initCollegeIndex()
      this.initCourseIndex()
      that.editorCtx.setContents({
        html: result.data.content,
        success: (res) => {
          console.log(res)
        },
        fail: (res) => {
          console.log(res)
        }
      })
    }

  },

  initCourseIndex: async function() {
    let courseIndex = this.data.courseIndex
    let post = this.data.post
    let courseInfo = this.data.courseInfo
    courseIndex[0] = this.getCourseIndex(courseInfo[0], post.college.year)
    courseIndex[1] = this.getCourseIndex(courseInfo[1], post.college.grade)
    courseIndex[2] = this.getCourseIndex(courseInfo[2], post.college.term)
    courseIndex[3] = this.getCourseIndex(courseInfo[3], post.college.credit)
    this.setData({
      courseIndex: courseIndex
    })
  },

  getCourseIndex: function(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        return i
      }
    }
  },

  initCourseInfo: function() {
    let year = new Date().getFullYear()
    let start = year - 10,
      end = year + 10
    let arr = [],
      i = 0,
      idx = 0
    for (; start < end; start++) {
      arr.push(start)
      if (start == year) {
        idx = i
      }
      i++
    }
    let cinfo = this.data.courseInfo
    let cindex = this.data.courseIndex
    cinfo[0] = arr
    cindex[0] = idx
    this.setData({
      courseInfo: cinfo,
      courseIndex: cindex
    })
  },

  initCollegeIndex: async function() {
    let colleges = this.data.colleges
    let post = this.data.post
    let collegeIndex = 0,
      majorIndex = 0
    for (var i = 0; i < colleges.length; i++) {
      if (colleges[i].name == post.college.name &&
        colleges[i].campus == post.college.campus) {
        collegeIndex = i
        majorIndex = colleges[i].majors.indexOf(post.college.major)
        break
      }
    }
    this.setData({
      collegeIndex: collegeIndex,
      majorIndex: majorIndex
    })
  },

  /**
   * 文章变化
   * @param {*} e 
   */
  changePostDetail: function(e) {
    let that = this;
    let post = that.data.post
    console.info(e)
    switch (e.target.id) {
      case 'postTitle':
        {
          post.title = e.detail.value
          break
        }
      case 'postTags':
        {
          post.tags = e.detail.value
          break
        }
      case 'postDigest':
        {
          post.digest = e.detail.value
          break
        }
      case 'postOriginalUrl':
        {
          post.originalUrl = e.detail.value
          break
        }
      case 'postTeacher':
        {
          if (post.college === undefined) {
            post.college = {}
          }
          post.college.teacher = e.detail.value
          break
        }
    }

    that.setData({
      post: post
    })
  },

  getPostCollegeInfo: function() {
    let college = this.data.post.college
    let c = this.data.colleges
    let cInfo = this.data.courseInfo
    let cIdx = this.data.courseIndex
    if (college !== undefined) {
      college.name = c[this.data.collegeIndex].name
      college.campus = c[this.data.collegeIndex].campus
      college.major = c[this.data.collegeIndex].majors[this.data.majorIndex]
      college.year = cInfo[0][cIdx[0]]
      college.grade = cInfo[1][cIdx[1]]
      college.term = cInfo[2][cIdx[2]]
      college.credit = cInfo[3][cIdx[3]]
    }
    return college
  },

  getAttach: async function() {
    let attach = []
    let title = this.data.post.title
    if (this.data.isFileChanged) {
      if (this.data.fileList.length > 0) {
        console.log('file len -> ', this.data.fileList.length)
        for (var idx in this.data.fileList) {
          let f = this.data.fileList[idx]
          console.log('file -> ', f)
          if (util.startWith(f.path, 'cloud://')) {
            attach.push({
              name: f.name,
              path: f.path
            })
          } else {
            let filePath = f.path
            let suffix = /\.[^\.]+$/.exec(filePath)[0];
            let result = await api.uploadFile('articles/' + title + '/' + Date.now() + suffix, f.path)
            console.log('upload file result -> ', result)
            if (result.statusCode == 200) {
              attach.push({
                name: f.name,
                path: result.fileID
              })
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '附件上传失败，请重试',
                icon: 'none',
                duration: 1500
              })
            }
          }
        }
        this.setData({
          isFileChanged: false,
          fileList: attach
        })
      }
    } else {
      attach = this.data.fileList
    }
    return attach
  },

  getImage: async function() {
    let post = this.data.post
    let title = this.data.post.title
    let img = ''
    if (this.data.isImgChanged) {
      if (this.data.imgList.length > 0) {
        let filePath = this.data.imgList[0].originPath
        let suffix = /\.[^\.]+$/.exec(filePath)[0];
        let result = await api.uploadFile('articles/' + title + '/' + Date.now() + suffix, this.data.imgList[0].originPath)
        console.log('upload file result -> ', result)
        if (result.statusCode == 200) {
          img = result.fileID
        } else {
          wx.hideLoading()
          wx.showToast({
            title: '图片上传失败，请重试',
            icon: 'none',
            duration: 1500
          })
          return
        }
      }
    } else {
      img = this.data.post.image
    }
    this.setData({
      isImgChanged: false
    })
    return img
  },

  /**
   * 除内容之外保存
   * @param {*} e 
   */
  savePostExceptContent: async function(e) {
    let that = this;
    let post = that.data.post

    if (post._id === undefined) {
      wx.showToast({
        title: '该操作仅支持更新哦',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    wx.showLoading({
      title: '保存中...',
    })

    let time = util.tsFormatTime(Date.now())
    let college = this.getPostCollegeInfo()
    let attach = await this.getAttach()
    let img = await this.getImage()

    let newPost = {
      digest: post.digest, //摘要
      title: post.title,
      originalUrl: post.originalUrl,
      updateTime: time,
      college: college,
      tags: this.getTags(), //标签
      image: img,
      attach: attach,
    }

    console.log('save 1 -> ', newPost)

    let result = await api.upsertPosts(post._id === undefined ? "" : post._id, newPost)
    if (result.result) {
      wx.hideLoading()
      wx.showToast({
        title: '基础信息保存成功',
        icon: 'none',
        duration: 1500
      })
    } else {
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 1500
      })
    }
  },
  /**
   * 保存文章
   * @param {*} e 
   */
  savePost: async function(e) {

    wx.showLoading({
      title: '保存中...',
    })

    let that = this;
    let post = that.data.post
    if (post.title === undefined || post.title == "") {
      wx.showToast({
        title: '标题不能为空',
        icon: 'none',
        duration: 1500
      })
      return;
    }

    let newPost
    let time = util.tsFormatTime(Date.now())
    let attach = await this.getAttach()
    let img = await this.getImage()
    let college = this.getPostCollegeInfo()
    let tags = this.getTags()

    if (post._id === undefined) {
      newPost = {
        author: app.globalData.userInfo.nickName,
        title: post.title,
        image: img,
        attach: attach,
        college: college,
        createTime: time,
        updateTime: time,
        comments: 0, //总的点评数
        downloads: 50 + Math.floor(Math.random() * 50), //下载
        views: 100 + Math.floor(Math.random() * 50), //总的访问数
        favors: 0, //总的收藏
        likes: 10 + Math.floor(Math.random() * 50), //总的点赞数
        tags: this.getTags(), //标签
        contentType: "html",
        digest: post.digest, //摘要
        isShow: 0, //是否展示
        originalUrl: post.originalUrl,
        content: this.data.content,
      }
    } else {
      newPost = {
        digest: post.digest, //摘要
        title: post.title,
        image: img,
        college: college,
        updateTime: time,
        content: this.data.content,
        attach: attach,
        tags: this.getTags(), //标签
        originalUrl: post.originalUrl
      }
    }

    console.log('save 2 -> ', newPost)

    let result = await api.upsertPosts(post._id === undefined ? "" : post._id, newPost)
    if (result.result) {
      wx.hideLoading()
      that.setData({
        isShowModel: true
      })
    } else {
      wx.hideLoading()
      wx.showToast({
        title: '保存失败',
        icon: 'none',
        duration: 1500
      })
    }
  },

  getTags() {
    let tags = this.data.post.tags
    console.log('tags -> ', tags)
    console.log('tags type -> ', typeof tags)
    if (tags !== undefined) {
      if ((typeof tags) == 'string') {
        console.log('tags string -> ', tags)
        return tags.split(',')
      } else {
        console.log('tags obj -> ', tags)
        return tags
      }
    }
    return []
  },

  undo() {
    this.editorCtx.undo()
  },
  redo() {
    this.editorCtx.redo()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  contentBlur: async function(e) {
    console.log('contentBlur ->', e)
    let that = this
    this.editorCtx.getContents({
      success: (e) => {
        console.log('getContent ->', e)
        that.setData({
          content: e.html
        })
      }
    })
  },
  onStatusChange(e) {},
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function() {
        console.log('insert divider success')
      }
    })
  },
  insertImage: async function(e) {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: async(res) => {
        console.log('insert image -> ', res.tempFilePaths)
        if (res.tempFilePaths.length > 0) {
          // this.editorCtx.insertImage({
          //   src: res.tempFilePaths[0],
          //   success: (e) => {
          //     console.log('insert image result ->', e)
          //   }
          // })
          let suffix = /\.[^\.]+$/.exec(res.tempFilePaths[0])[0];
          let result = await api.uploadFile('articles/images/' + Date.now() + suffix, res.tempFilePaths[0])
          console.log('upload image result -> ', result)
          if (result.statusCode == 200) {
            this.editorCtx.insertImage({
              src: result.fileID
            })
          } else {
            wx.showToast({
              title: '图片上传失败，请重试',
              icon: 'none',
              duration: 1500
            })
          }
        }
      }
    });

  },
  clear() {
    this.editorCtx.clear({
      success: function(res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  /**
   * 获取富文本内容
   */
  getContent: function() {
    let that = this
    return new Promise((resolve, rej) => {
      that.editorCtx.getContents({
        success: (res) => {
          resolve('html -> ', res)
        },
        fail: res => {
          console.log("请求失败")
        }
      })
    })
  },

  chooseMsgFile() {
    let that = this;
    wx.chooseMessageFile({
      count: 5,
      type: 'file',
      success(res) {
        console.log('choose file -> ', res);
        if (res.tempFiles.length > 0) {
          that.setData({
            fileList: that.data.fileList.concat(res.tempFiles),
            isFileChanged: true
          })
        }
      }
    })
  },


  delMsgFile(e) {
    wx.showModal({
      title: '删除附件',
      content: '确定要删除该附件吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.fileList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            fileList: this.data.fileList
          })
        }
      }
    })
  },

  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        this.setData({
          imgList: this.data.imgList.concat({
            originPath: res.tempFilePaths[0],
            httpPath: res.tempFilePaths[0]
          }),
          isImgChanged: true
        })
      }
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '删除图片',
      content: '确定要删除该图片吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  /**
   * 设置隐藏
   * @param {*} e 
   */
  hideShowModal: function(e) {
    this.setData({
      // post: {},
      // imgList: [],
      isShowModel: false
    })
  },
  showArticleList: function(e) {
    wx.navigateBack({
      delta: 1
    })
  },
  clearAll: function(e) {
    this.setData({
      post: {},
      imgList: [],
      fileList: [],
    })
  },

  bindPickerChange: function(e) {
    console.log('picker ->', e)
    switch (e.currentTarget.id) {
      case 'college':
        {
          this.setData({
            collegeIndex: e.detail.value,
          })
          break
        }
      case 'major':
        {
          this.setData({
            majorIndex: e.detail.value,
          })
          break
        }
      default:
    }

  },

  bindMultiPickerChange: function(e) {
    console.log('multi picker ->', e)
    this.setData({
      courseIndex: e.detail.value
    })
  },

})